﻿namespace dotnet_notes.Extensions
{
    /// <summary>
    /// SqlSugar 扩展类
    /// </summary>
    public static class SqlSugarExtension
    {
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="pageNumber">页数</param>
        /// <param name="pageSize">行数</param>
        /// <returns></returns>
        public static async Task<PageList> GetPageListAsync<T>
            (this ISugarQueryable<T> queryable, int pageNumber, int pageSize) where T : class
        {
            RefAsync<int> totalNumber = 0;
            RefAsync<int> totalPage = 0;

            var list = await queryable.ToPageListAsync(pageNumber, pageSize, totalNumber, totalPage);

            return new PageList
            {
                TotalNumber = totalNumber,
                TotalPage = totalPage,
                List = list
            };
        }

        /// <summary>
        /// 存在检查(存在会抛出异常)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="whereExpression">查询的条件</param>
        /// <param name="exceptionMessage">异常信息(默认是名称重复)</param>
        /// <returns></returns>
        public static async Task CheckExistsAsync<T>(this ISugarQueryable<T> queryable,
            Expression<Func<T, bool>> whereExpression, 
            string exceptionMessage = MessageConfig.NameDuplicate)
        {
            if (await queryable.Where(whereExpression).AnyAsync())
            {
                throw new InvalidOperationException(exceptionMessage);
            }
        }

        /// <summary>
        /// 获取记录(不存在会抛出异常)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="whereExpression">查询的条件</param>
        /// <returns></returns>
        public static async Task<T> GetFirstAsync<T>
            (this ISugarQueryable<T> queryable, Expression<Func<T, bool>> whereExpression)
        {
            return await queryable.FirstAsync(whereExpression) 
                ?? throw new InvalidOperationException(MessageConfig.NotExists);
        }
    }
}
